const path = require('path')
const ts = require('rollup-plugin-typescript')
const json = require('@rollup/plugin-json')
const nodeResolve = require('@rollup/plugin-node-resolve')
const commonjs = require('@rollup/plugin-commonjs')

const target = process.env.TARGET
const sourcemap = process.env.SOURCEMAP
const packageFormats = process.env.FORMATS && process.env.FORMATS.split('-')

console.log(target, packageFormats, sourcemap);

//根据target找到对应的包
const packagesDir = path.resolve(__dirname, 'packages')
const packageDir = path.resolve(packagesDir, target)//要打包的入口比如 packages/reactivity

const resolve = (p) => path.resolve(packageDir, p)

const name = path.basename(packageDir) // 比如reactivity
const pkg = require(resolve(`package.json`))

const outputConfig = {
    'esm-bundle':{
        file: resolve(`dist/${name}.esm-bundler.js`),
        format: 'es'
    },
    'cjs':{
        file: resolve(`dist/${name}.cjs.js`),
        format: 'cjs'
    },
    'global':{
        file: resolve(`dist/${name}.global.js`),
        format: 'iife'
    },
}

const packageConfig =  packageFormats || pkg.buildOptions.formats

const createConfig = (format, output) => {
    output.sourcemap = sourcemap
    output.exports = 'named'
    let external = []
    if(format === 'global'){
        output.name = pkg.buildOptions.name
    }else {
        external = [...Object.keys(pkg.dependencies)]
    }
    return {
        input: resolve('src/index.ts'),
        output,
        external,
        plugins: [
            json(),
            ts(),
            nodeResolve(),
            commonjs(),
            
        ]
    }
}

module.exports = packageConfig.map(format => createConfig(format, outputConfig[format]))